<?php

include "vendor/autoload.php";
set_time_limit(0);
ignore_user_abort(true);
ini_set("memory_limit", '2048M');
date_default_timezone_set('Asia/Shanghai');

use think\facade\Db;

use Zeroibc\DingDingRobot;

// 数据库配置信息设置（全局有效）
Db::setConfig(
    [
        // 默认数据连接标识
        'default' => 'mysql',
        // 数据库连接信息
        'connections' => [
            'mysql' => [
                // 数据库类型
                'type' => 'mysql',
                // 主机地址
                'hostname' => '127.0.0.1',
                // 用户名
                'username' => 'video',
                // 数据库密码
                'password' => 'wwLizyT5CSYB5it5',
                // 数据库名
                'database' => 'video',
                // 数据库编码默认采用utf8
                'charset' => 'utf8',
                // 数据库表前缀
                'prefix' => 'mac_',
                // 数据库调试模式
                'debug' => true,
                'break_reconnect' => true
            ],
        ],
    ]
);

function sendDingding($message)
{
//    return;
    $web_hook = 'https://oapi.dingtalk.com/robot/send?access_token=f4f7b410307f097a8f65077c906fc2c7740618aab4ab5849dcc509f182c832dc';
    $robot = new DingDingRobot($web_hook);
    $content = [
        'content' => '[直播爬取通知]：' . $message . ' ',
    ];
    $robot->setTextType()->setContent($content)->send();
}


function selfLog()
{
    ob_start();
    $args = func_get_args();
    var_export(date('Y-m-d H:i:s') . '-' . microtime(true));
    foreach ($args as $arg) {
        echo json_encode($arg, JSON_UNESCAPED_UNICODE) . "\n";
    }
    echo "\n\r";
    ob_flush();
    ob_end_flush();
}

function getTypeId($type)
{
//    switch ($type){
//        case '足球':
//            return 41;
//        case '篮球':
//            return 42;
//        case '电子竞技':
//            return 43;
//        default:
//
//
//    }
    $id = Db::name('zhibo_type')->cache(true)->where('name', $type)->value('id');
    selfLog('当前分类ID' . $id);
    if (empty($id)) {
        $id = Db::name('zhibo_type')->insertGetId(['name' => $type]);
        selfLog('创建数据库 分类ID' . $id);
    }
    return $id;
}

$zhiboUrl = "https://www.video.7q173.cn/live/";

$jiekou = "https://www.bit166.com/api/list?key=177f7e21df5fda1842357cbedcbcff23";
$timeStart = microtime(true);
selfLog('开始获取数据');
$list = file_get_contents($jiekou);
if (empty($list)) {
    sendDingding('未能获取到数据!');
    sleep(60);
    exit;
}
$list = json_decode($list, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    selfLog('json解析出错！', json_last_error(), json_last_error_msg());
    sendDingding('json解析出错');
    exit;
}
selfLog('json转数组处理结束');
$zhiboIds = [];
$nums = count($list);
$youxiaoIndex = 0;
selfLog('共计数据' . $nums . '条');
$nums = [];
foreach ($list as $index => $item) {
    $item['Liga'] = trim($item['Liga']);
    selfLog('正在处理' . $index);
    $typeId = getTypeId($item['Sport']);
    if ($typeId === false) {
        selfLog('当前项目不是三个分类中的，跳过');
        continue;
    }
    if (!isset($nums[$typeId])) {
        $nums[$typeId] = [];
    }
    $youxiaoIndex++;
    selfLog($item);
    //处理直播状态
    $zhiboStatus = $item['StreamInfo']['state'] === true ? 1 : 0;
    if ($item['MatchInfo']['PlayingTime'] > 0) {
        if ($zhiboStatus === 0) {
            selfLog('当前比赛已经进行 直播流异常，状态改为中断');
            $zhiboStatus = 2;
        }

//        if(in_array($typeId,[41,42]) && $zhiboStatus==2){
//            selfLog('当前比赛已经进行 直播流异常，属于足球和篮球 忽略状态中断，保持状态为直播中');
//            $zhiboStatus=1;
//        }
    }
    if ($zhiboStatus == 1) {
        //处理直播地址
        if (!empty($item['StreamType'])) {
            $gaodingUrl = '高清$' . $zhiboUrl . $item['StreamName'] . '.m3u8';
            $biaoqingUrl = '标清$' . $zhiboUrl . str_replace($item['StreamType'], '', $item['StreamName']) . '.m3u8';
            $zhiboUrls = $biaoqingUrl . '###' . $gaodingUrl;
        } else {
            $zhiboUrls = '标清$' . $zhiboUrl . $item['StreamName'] . '.m3u8';
        }
    } else {
        $zhiboUrls = '';
    }
    $data = [
        'zhibo_name' => $item['Liga'],
        'zhibo_time' => $item['Matchtime'],
        'zhibo_score' => str_replace('-', '$', $item['Scores']),
        'zhibo_qiudui' => $item['Opp1'] . '$' . $item['Opp2'],
        'type_id' => $typeId,
        'type_id_1' => 40,
        'zhibo_status' => $zhiboStatus,
        "zhibo_play_url" => $zhiboUrls,
        'zhibo_img' => ''
    ];
    $existData = Db::name('zhibo')->where('type_id', $typeId)->where('zhibo_name', $item['Liga'])->where('zhibo_qiudui', $data['zhibo_qiudui'])->find();
    selfLog(Db::name('zhibo')->getLastSql());
    if (isset($existData)) {
        $zhiboIds[] = $existData['zhibo_id'];
        Db::name('zhibo')->where('zhibo_id', $existData['zhibo_id'])->update($data);
        selfLog('更新数据', Db::name('zhibo')->getLastSql());
    } else {
        $zhiboId = Db::name('zhibo')->insertGetId($data);
        $zhiboIds[] = $zhiboId;
        selfLog('插入数据', Db::name('zhibo')->getLastSql());
    }

    //处理分类情况
    $sortArray = [
        'type_id' => $typeId,
        'raw_name' => $item['Liga']
    ];

    $isExistSortArray = Db::name('zhibo_sort')->where($sortArray)->find();
    if (empty($isExistSortArray)) {
        $sortId = Db::name('zhibo_sort')->insertGetId($sortArray);
        selfLog('写入新的比赛名称' . Db::name('zhibo_sort')->getLastSql());
    } else {
        $sortId = $isExistSortArray['id'];
        selfLog('比赛名称 已存在' . Db::name('zhibo_sort')->getLastSql());
    }
    if (!isset($nums[$typeId][$sortId])) {
        $nums[$typeId][$sortId] = 1;
    } else {
        $nums[$typeId][$sortId]++;
    }


}
$needDeleteIds = Db::name('zhibo')->whereNotIn('zhibo_id', $zhiboIds)->column('zhibo_id');

if (!empty($needDeleteIds)) {
//找到广告相关的直播ID 然后将数据copy到 zhibo_ad表 标记为已删除
    $update = Db::name('zhibo')->whereIn('zhibo_id', $needDeleteIds)->delete();

    selfLog(Db::name('zhibo')->getLastSql());
} else {
    $update = 0;
}
selfLog('当前分类数组',$nums);
Db::name('zhibo_sort')->where('id','>',0)->update(['num'=>0]);
//处理赛事数量
foreach ($nums as $typeId =>$sortArray){
    foreach ($sortArray as $sortId=>$nums){
        Db::name('zhibo_sort')->where('id',$sortId)->update(['num'=>$nums]);
        selfLog(Db::name('zhibo_sort')->getLastSql());
    }
}


$timeEnd = microtime(true);
$spendTime = $timeEnd - $timeStart;
selfLog('当前获取数据' . $nums . '条，有效数据' . $youxiaoIndex . '条,删除数据' . $update . '条,共计执行时间为' . $spendTime . '秒');
//sendDingding('本次获取数据'.$nums.'条，有效数据'.$youxiaoIndex.'条,删除数据'.$update.'条,共计执行时间为'.$spendTime.'秒');
//sleep(10);